<?php

namespace Shahu\Common\model;

use Shahu\Common\enum\DeleteEnum;
use support\Db;

trait SortModel
{
    private static string $column_sort = 'sort';

    /**
     * 获取最大排序数
     * @return int
     */
    public static function selectMaxSort(): int
    {
        $column = ['max(sort) as max_sort'];

        $result = Db::table(static::$table_name)
            ->select($column)
            ->where(static::$delete_field, (DeleteEnum::LIVE)->value)
            ->limit(1)
            ->first();
        //处理结果
        $res = static::handleSelectResult($result);
        return $res['max_sort'] ?? 0;
    }


    /**
     * 获取最小排序数
     * @return int
     */
    public static function selectMinSort(): int
    {
        $column = ['min(sort) as max_sort'];

        $result = Db::table(static::$table_name)
            ->select($column)
            ->where(static::$delete_field, (DeleteEnum::LIVE)->value)
            ->limit(1)
            ->first();
        //处理结果
        $res = static::handleSelectResult($result);
        return $res['min_sort'] ?? 0;
    }


    /**
     * 查询更小的一个排序号
     * @param int $sort
     * @return array
     */
    public static function selectLessSort(int $sort = 0): array
    {
        $column = ['id', 'sort', 'status'];

        $result = Db::table(static::$table_name)
            ->select($column)
            ->where(static::$column_sort, '<', $sort)
            ->where(static::$delete_field, (DeleteEnum::LIVE)->value)
            ->orderBy(static::$column_sort, 'desc')
            ->limit(1)
            ->first();
        //处理结果
        return static::handleSelectResult($result);
    }


    /**
     * 查询更大的排序号
     * @param int $sort
     * @return array
     */
    public static function selectGreaterSort(int $sort = 0): array
    {
        $column = ['id', 'sort', 'status'];

        $result = Db::table(static::$table_name)
            ->select($column)
            ->where(static::$column_sort, '>', $sort)
            ->where(static::$delete_field, (DeleteEnum::LIVE)->value)
            ->orderBy(static::$column_sort)
            ->limit(1)
            ->first();
        //处理结果
        return static::handleSelectResult($result);
    }
}
